package cn.anc.aonicardv.module.ui.album;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.R2;
import cn.anc.aonicardv.bean.AlbumBean;
import cn.anc.aonicardv.bean.PhotoBean;
import cn.anc.aonicardv.event.BigImageDataEvent;
import cn.anc.aonicardv.event.LocalDeleteEvent;
import cn.anc.aonicardv.event.LongClickEditEvent;
import cn.anc.aonicardv.module.adpter.album.PhotoAdapter;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemClickListener;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemLongClickListener;
import cn.anc.aonicardv.module.ui.base.BaseFragment;
import cn.anc.aonicardv.net.download.DownLoadManager;
import cn.anc.aonicardv.util.ActivityUtils;
import cn.anc.aonicardv.util.AoniBeanDecorationUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.MediaScanner;
import cn.anc.aonicardv.util.ViewUtil;
import cn.anc.aonicardv.widget.AlbumDecoration;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.cache.CacheManager;

/**
 * Created by yangdai on 2017/5/18.
 */

public class PhotoFragment extends BaseFragment implements MediaScanner.ScanCompleteCallBack, MediaScannerConnection.OnScanCompletedListener, OnAlbumItemLongClickListener, OnAlbumItemClickListener {

    @BindView(R2.id.iv_loading)
    ImageView loadingIv;
    @BindView(R2.id.rv_photo)
    RecyclerView photoRv;



    private PhotoAdapter photoAdapter;
    private List<PhotoBean> photoBeanList;
    private List<AlbumBean> result;
    private List<PhotoBean> deleteBeans = new ArrayList<>();
    private Handler handler = new Handler();
    private ProgressDialog progressDialog;
    private AlbumDecoration decoration;
    public List<AlbumDecoration.DecorationBean> decorationBeanList;
    private DialogUtils dialogUtils;
    GridLayoutManager gridLayoutManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView(R.layout.fragment_photo);
    }

    @Override
    public void initVariable() {
        photoAdapter = new PhotoAdapter(this);
        dialogUtils = new DialogUtils();
        progressDialog = dialogUtils.getProgressDialog(getContext());
        gridLayoutManager = null;

    }

    private View mLayoutNoDataView;
    @Override
    public void findViewById(View view) {
        mLayoutNoDataView = view.findViewById(R.id.layout_no_data_view);
    }

    @Override
    public void setListener() {
        photoAdapter.setOnItemClickListener(this);
        photoAdapter.setOnItemLongClickListener(this);
    }

    @Override
    public void initData() {
        photoAdapter.registerEventBusForAdapter();
        updateUI();
    }
    private Handler mHandler = new Handler();
    @Override
    public void onResume() {
        super.onResume();
        if (photoBeanList == null || photoBeanList.isEmpty()) {
            ViewUtil.showContentLayout(Constant.LAYOUT_EMPTY, mLayoutNoDataView, photoRv,R.mipmap.photo_empty,getActivity().getResources().getString(R.string.photo_empty_hint));
        } else {
            ViewUtil.showContentLayout(Constant.LAYOUT_DATA, mLayoutNoDataView, photoRv);
        }
        photoAdapter.notifyDataSetChanged();
        setDecoration();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LocalDeleteEvent event) {
        progressDialog.setMessage(getString(R.string.recorder_album_delete_file_hint));
        progressDialog.setCancelable(false);
        progressDialog.show();
        for (int i = 0; i < photoBeanList.size(); i++) {
            if (photoBeanList.get(i).isCheck()) {
                boolean b = new File(photoBeanList.get(i).getPath()).delete();
                if (b) {
                    deleteBeans.add(photoBeanList.get(i));
                }
            }
        }
        if (deleteBeans.size() > 0) {
            photoBeanList.removeAll(deleteBeans);
            deleteBeans.clear();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateUI();
                    progressDialog.dismiss();
                    Toast.makeText(MyApplication.getInstance(), getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
                }
            });
//            MediaScannerConnection.scanFile(getContext(), new String[]{deleteBeans.get(0).getPath()}, null, this);

        } else {
            progressDialog.dismiss();
        }
    }

    @Override
    public void scanComplete(final Cursor cursor) {
        photoBeanList = getPhotoBeanList(cursor);
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (photoRv != null) {
                    updateUI();
                }
            }
        });
    }




    private void updateUI() {
        if (photoBeanList != null)
            loadingIv.setVisibility(View.VISIBLE);
        if (photoBeanList != null && photoBeanList.isEmpty()) {
            loadingIv.setVisibility(View.INVISIBLE);
            ViewUtil.showContentLayout(Constant.LAYOUT_EMPTY, mLayoutNoDataView, photoRv,R.mipmap.photo_empty,getActivity().getResources().getString(R.string.photo_empty_hint));
        } else if (photoBeanList != null && !photoBeanList.isEmpty()) {
            ViewUtil.showContentLayout(Constant.LAYOUT_DATA, mLayoutNoDataView, photoRv);
            loadingIv.setVisibility(View.INVISIBLE);
        }
        photoAdapter.setData(photoBeanList);
        photoRv.setAdapter(photoAdapter);
        setDecoration();
    }

    private void setDecoration() {
        result = AlbumBean.getClassifyAlbumBeanByPhotoBean(photoBeanList);
        decorationBeanList = getDecorationBeanByAlbumBean(result);
        if (gridLayoutManager == null) {
            gridLayoutManager = new GridLayoutManager(getContext(), 3);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return AoniBeanDecorationUtils.getSpanSize(decorationBeanList, position);
                }
            });
            photoRv.setLayoutManager(gridLayoutManager);
        }
        if (decoration != null) {
            photoRv.removeItemDecoration(decoration);
        }
        decoration = new AlbumDecoration(decorationBeanList);
        photoRv.addItemDecoration(decoration);
    }

    private List<AlbumDecoration.DecorationBean> getDecorationBeanByAlbumBean(List<AlbumBean> result) {
        List<AlbumDecoration.DecorationBean> temp = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            AlbumDecoration.DecorationBean d = new AlbumDecoration.DecorationBean(result.get(i).getPosition(), result.get(i).getDate(), result.get(i).getPhotoBeanList().size());
            temp.add(d);
        }
        return temp;
    }

    public int getPhotoNum() {

        return photoBeanList == null ? 0 : photoBeanList.size();
    }

    public PhotoBean getSelectedPhotoBean() {
        for (int i = 0; i < photoBeanList.size(); i++) {
            if (photoBeanList.get(i).isCheck()) {
                return photoBeanList.get(i);
            }
        }
        return null;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            EventBus.getDefault().unregister(this);
        } else {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (getUserVisibleHint() && resultCode == 200) {
            MediaScanner.scanImages(DownLoadManager.PHOTO_PATH, this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        photoAdapter.unregisterEventBusForAdapter();
    }

    public List<PhotoBean> getPhotoBeanList(Cursor cursor) {
        List<PhotoBean> photoBeanList = new ArrayList<>();
        while (cursor.moveToNext()) {
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            if (!new File(path).exists())
                continue;
            long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID));
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
            CarControl.CarDvThumbnailMediaInfo mediaInfo = CacheManager.getMediaInfoFromExif(path);
            String resolution;
            String fileTime;
            if (mediaInfo != null) {
                resolution = mediaInfo.resolution;
                fileTime = mediaInfo.file_time;
                if (!TextUtils.isEmpty(mediaInfo.file_time) && mediaInfo.file_time.contains(" ")) {
                    PhotoBean photoBean = new PhotoBean(mediaInfo.file_time.split(" ")[0], path, name, resolution, fileTime);
                    photoBeanList.add(photoBean);
                }
            }
        }
        cursor.close();
        return photoBeanList;
    }

    @Override
    public void onScanCompleted(String path, Uri uri) {
        photoBeanList.remove(deleteBeans.get(0));
        deleteBeans.remove(0);
        if (deleteBeans.size() > 0) {
            MediaScannerConnection.scanFile(getContext(), new String[]{deleteBeans.get(0).getPath()}, null, this);
        } else {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    updateUI();
                    progressDialog.dismiss();
                    Toast.makeText(MyApplication.getInstance(), getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }


    @Override
    public void onItemLongClick(View view, int position, boolean isEditMode) {
        EventBus.getDefault().post(new LongClickEditEvent());
    }

    @Override
    public void onItemClick(CheckBox selectCb, int position, boolean isEditMode) {
        if (!isEditMode) {
            if (result == null)
                return;
            ActivityUtils.jumpActivityForResult(getActivity(), BigImageActivity.class, Constant.IntentKeyParam.POSITION, position, 10000);
            EventBus.getDefault().postSticky(new BigImageDataEvent(photoBeanList));
        } else {
            selectCb.setPressed(true);
            if (selectCb.isChecked()) {
                selectCb.setChecked(false);
            } else
                selectCb.setChecked(true);
            selectCb.setPressed(false);
        }
    }


}
